package wxdb.planner;

import wxdb.query.*;
import wxdb.record.*;
import wxdb.ui.Global;
import wxdb.index.btree.BTreeIndex;
import wxdb.metadata.IndexInfoMgr;
import wxdb.metadata.TableMgr;
import wxdb.parse.*;
import wxdb.parse.absyn.*;
import java.util.*;

import static java.sql.Types.*;

/**
 * The simplest, most naive query planner possible.
 * @author Edward Sciore
 */
public class BasicQueryPlanner {
   /**
    * Creates a query plan as follows.  It first takes
    * the product of all tables and views; it then selects on the predicate;
    * and finally it projects on the field list. 
    */
   public HashMap<String,ArrayList> excuteQuery(QryExp data) {

      //Step 1: Create a plan for each mentioned table
	  boolean times = true;
	  boolean nowhere = true;
	  HashMap<String,ArrayList> result = new HashMap<String,ArrayList>();
	  
	  HashMap<String,HashMap<String,ArrayList>> projecthm = new HashMap<String,HashMap<String,ArrayList>>();
	  //select
      for (String tblname : data.tables()) {
    	  HashSet<RID> selectses = TableMgr.selectTable(tblname, data.pred());
    	  projecthm.put(tblname, new HashMap<String,ArrayList>());
    	  //project
          for(String field : data.fields().get(tblname)){
        	  ArrayList projectres = TableMgr.projectTable(field,selectses,tblname);
        	  projecthm.get(tblname).put(field, projectres);
          }
      }
      //product
      if(data.tables().size()>1){
          ArrayList<String> al = new ArrayList<String>(data.tables());
          String firsttbl = al.remove(0);
          result = projecthm.get(firsttbl);
    	  for(String tbl : al){
    		  result = TableMgr.productTable(result,projecthm.get(tbl));
    	  }
      }else{
    	  if(Global.REFRESHTABLE == true){
    		  Global.REFRESHTABLE = false;
    		  String tblname = data.tables().get(0);
    		  Global.queryFields.addAll(data.fields().get(tblname));
    		  for(String field : data.fields().get(tblname))
    			  Global.queryResult.addAll(projecthm.get(tblname).get(field));
    	  }else{
    		  String tblname = data.tables().get(0);
    		  for(String field : data.fields().get(tblname)){
    			  result.put(field, new ArrayList());
    			  result.get(field).addAll(projecthm.get(tblname).get(field));
    		  }
    	  }
      }
      return result;
   }
}
